package com.features;

import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;

import com.utils.AbstractTrace;

/** <p>Title: CPU相关操作</p>
 * <p>Description: 获取CPU资源信息</p>
 * <p>Copyright: Copyright (c) 2011</p>
 * @author zhangzuoqiang
 * @version 1.0
 * <br/>Date: 2011-5-10
 */
public class CPUCommand extends AbstractTrace {
	
	/**
	 * 获取CPU数目
	 * @return
	 * @throws SigarException
	 */
	public int getCpuCount() {
		Sigar sigar = new Sigar();
		try {
			return sigar.getCpuInfoList().length;
		} catch (SigarException e) {
			e.printStackTrace();
			return -1;
		} finally {
			sigar.close();
		}
	}
	
	/**
	 * CPU的总量（单位：HZ）及CPU的相关信息
	 * @throws SigarException
	 */
	public CpuInfo[] getCpuInfos() {
		Sigar sigar = new Sigar();
		CpuInfo infos[] = null;
		try {
			infos = sigar.getCpuInfoList();
		} catch (SigarException e) {
			e.printStackTrace();
		}
		//不管是单块CPU还是多CPU都适用
		/*for (int i = 0; i < infos.length; i++) {
			CpuInfo info = infos[i];
			traceln("mhz=" + info.getMhz());//CPU的总量MHz
			traceln("vendor=" + info.getVendor());//获得CPU的卖主，如：Intel
			traceln("model=" + info.getModel());//获得CPU的类别，如：Celeron
			traceln("cache size=" + info.getCacheSize());//缓冲存储器数量
		}*/
		return infos;
	}	
	
	/**
	 * 得到当前cpu状态信息, 不管是单块CPU还是多CPU都适用
	 */
	public CpuPerc[] getCpuPerc() {
		Sigar sigar = new Sigar();
        CpuPerc cpuList[] = null;
        try {
        	cpuList = sigar.getCpuPercList();
        } catch (SigarException e) {
        	e.printStackTrace();
        }
        return cpuList ;
     }
	
	/**
	 * 输出cpui当前状态信息
	 * @param cpu
	 */
	public void printCpuPerc(CpuPerc cpu[]) {
		for (int i = 0; i < cpu.length; i++) {
			traceln("User :" + CpuPerc.format(cpu[i].getUser()));// 用户使用率
			traceln("Sys :" + CpuPerc.format(cpu[i].getSys()));// 系统使用率
			traceln("Wait :" + CpuPerc.format(cpu[i].getWait()));// 当前等待率
			traceln("Nice :" + CpuPerc.format(cpu[i].getNice()));//
	        traceln("Idle :" + CpuPerc.format(cpu[i].getIdle()));// 当前空闲率
	        traceln("Total :" + CpuPerc.format(cpu[i].getCombined()));// 总的使用率
		}
    }
}
